package com.snail.service.impl;

import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.exception.BusinessException;
import com.snail.exception.ErrorCode;
import com.snail.mapper.SysTeamUserMapper;
import com.snail.model.pojo.SysTeam;
import com.snail.model.pojo.SysTeamUser;
import com.snail.service.SysTeamService;
import com.snail.service.SysTeamUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author Monica
 * @description 针对表【sys_team_user(用户与战队关联表)】的数据库操作Service实现
 * @createDate 2025-07-23 14:30:24
 */
@Service
public class SysTeamUserServiceImpl extends ServiceImpl<SysTeamUserMapper, SysTeamUser>
        implements SysTeamUserService {

    @Autowired
    private SysTeamService sysTeamService;

    /**
     * 申请加入战队
     */
    @Override
    public Boolean applyJoinTeam(SysTeamUser sysTeamUser) {
        // 检查战队是否存在且未解散
        SysTeam team = sysTeamService.getById(sysTeamUser.getTeamId());
        if (team == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "战队不存在或已解散");
        }

        // 检查用户是否是战队创建者
        if (team.getCreatorId().equals(sysTeamUser.getUserId())) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不能加入自己创建的战队");
        }

        // 检查用户是否已经是战队管理员或成员
        LambdaQueryChainWrapper<SysTeamUser> userExist = this.lambdaQuery()
                .eq(SysTeamUser::getTeamId, sysTeamUser.getTeamId())
                .eq(SysTeamUser::getUserId, sysTeamUser.getUserId());

        SysTeamUser existingRelation = userExist.one();
        if (existingRelation != null) {
            if (existingRelation.getRole() > 0) { // 如果role>0表示是管理员角色
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "您已经是该战队的管理员");
            } else {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "您已经加入该战队");
            }
        }

        // 检查战队人数是否已满
        long currentMembers = this.lambdaQuery()
                .eq(SysTeamUser::getTeamId, sysTeamUser.getTeamId())
                .eq(SysTeamUser::getStatus, 0) // 只统计正式成员
                .count();
        if (currentMembers >= team.getMaxCount()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "战队人数已满");
        }

        // 设置加入时间和角色
        sysTeamUser.setJoinTime(new Date());
        sysTeamUser.setRole(0); // 默认普通成员

        // 根据战队设置决定是否需要审核
        if (team.getNeedReview() == 1) {
            sysTeamUser.setStatus(1); // 需要审核
        } else {
            sysTeamUser.setStatus(0); // 直接加入
        }

        return this.save(sysTeamUser);
    }

}




